import { getSuitableCards } from "../util/CardUtil";
import { AudioType, BtnColor, CardColor, CardINF, CardLocation, CardNodeMap, CardStatus, CardType, CurrentPlayer, explainType, ListenEventType, playerPeople } from "../util/defineConfig";
import OnEventMode from "../util/OnEventMode";
import UICard from "./UIComponent/UICard";

const { ccclass, property } = cc._decorator;

//Event表示事件是派发的

// 卡牌类
export class Card {
    public color: CardColor = CardColor.red
    public type: CardType = CardType.number
    public index: number = 0
    public UICard: UICard = null
    public status: CardStatus = CardStatus.CLOSE
    public spriteFrame: cc.SpriteFrame = null
    public location: CardLocation = CardLocation.sendCardArea
    public belongTo: number = 0
    // 能否被点击
    public canClick: boolean = true
    // 被选中
    public selected: boolean = false
    
    constructor(color: CardColor, type: CardType, index: number, status: CardStatus = CardStatus.CLOSE, spriteFrame: cc.SpriteFrame, belongTo: number = 0) {
        this.color = color
        this.type = type
        this.index = index
        this.status = status
        this.spriteFrame = spriteFrame
        this.belongTo = belongTo
        this.canClick = true
        this.selected = false
    }

    public bindView(UICard: UICard) {
        this.UICard = UICard
    }

    public flopCard() {
        this.status = CardStatus.OPEN
        this.UICard.flopCard(this.spriteFrame)
    }

    public level() {
        let level = 10;
        if (this.color == CardColor.blue && this.index == 3) return level;

        level--;
        if (this.color == CardColor.red && this.index == 19) return level;

        level--;
        if (this.color == CardColor.red && this.index == 18) return level;

        level--;
        if (this.index == 7) return level;

        level--;
        if (this.index == 2) return level;

        level--;
        return level;
    }

    /**
     * 是否硬主 大于等于2的就是硬主
     * @param card 
     * @returns 
     */
    public isHardMaster(): boolean {
        return this.level() >= new Card(CardColor.red, CardType.number, 2, CardStatus.CLOSE, null).level()
    }

    /**
     * 是否主，花色对的上 是硬主
     * @param card 
     * @returns 
     */
    public isMaster(color: CardColor): boolean {
        if (this.isHardMaster()) return true;

        return this.color === color
    }

    public showGreater(card: Card, currentColor: CardColor = CardColor.special): boolean {
        if (this.index == card.index && this.color == card.color) return true;

        let l1 = this.level()
        let l2 = card.level()
        if (l1 != l2) {
            return l1 - l2 >= 0 ? true : false;
        }

        //等级相同
        if (this.color == card.color) {//同样花色
            return this.index - card.index >= 0 ? true : false;
        }

        if (this.color === currentColor) return true;
        if (card.color === currentColor) return false;

        return this.color - card.color >= 0 ? true : false;
    }

    public greater(c2: Card, currentColor: CardColor = CardColor.special): boolean {
        if (this.index == c2.index && this.color == c2.color) return false;

        let l1 = this.level()
        let l2 = c2.level()

        if (l1 != l2) {
            return l1 > l2;
        }

        //等级相同
        if (this.color == c2.color) {//同样花色
            return this.index > c2.index//比较数字大小
        }

        if (this.color === currentColor) return true;
        if (c2.color === currentColor) return false;

        //2个都不是主，不会比它大的
        return false;
    }

    public getCardPoint(): number {
        if (this.index == 5) return 5;

        if (this.index == 10 || this.index == 13) return 10;

        return 0;
    }
}

class Player {
    public index: number
    public playedCard: Card[] //打出去的牌
    public points: number

    constructor(index: number) {
        this.index = index
        this.playedCard = []
        this.points = 0
    }

    public addPoints(points: number) {
        this.points += points
    }
    public getPonits() {
        return this.points
    }

    public addPlayedCard(card: Card) {
        this.playedCard.push(card)
    }

    public getLatestCard(): Card {
        return this.playedCard[this.playedCard.length - 1]
    }
}

//玩牌区类
export class playerCardArea {
    public cards: Card[] = []

    public addCards(card: Card, color = CardColor.yellow): number {
        let fIndex = this.cards.findIndex(element => {
            return card.showGreater(element, color)
        });
        if (fIndex === -1) fIndex = this.cards.length
        this.cards.splice(fIndex, 0, card)

        return fIndex
    }

    //查找对应颜色卡牌
    public findCardByColor(color: CardColor, index: number): Card {
        let card: Card = null
        // 是否有相同的花色
        let hasCard = this.cards.some((item) => {
            if (item.color === color) {
                card = item
                return true
            }
            return false
        })
        if (!hasCard) {
            // 是否有相同的点数
            let hasSameIndex = this.cards.some((item) => {
                if (item.index === index && item.color !== CardColor.special) {
                    card = item
                    return true
                }
                return false
            })
            //是否有特殊牌
            if (!hasSameIndex) {
                this.cards.some((item) => {
                    if (item.color === CardColor.special) {
                        card = item
                        return true
                    }
                    return false
                })
            }

        }
        return card ? card : this.cards[0]
    }

    // 牌区没牌？
    public isEmptyCard() {
        return this.cards.length === 0
    }

    // 牌区只剩一张？
    public isRemainOneCard() {
        return this.cards.length === 1
    }

    // 这张牌能不能出？
    public isShowCard(card: Card, color: CardColor, index: number): boolean {
        if (card.color === color) { return true }
        else if (card.index === index && card.color !== CardColor.special) { return true }
        else if (card.color === CardColor.special) { return true }
        else { return false }
    }

    // 删除指定牌
    public removeCard(card: Card) {
        this.cards.some((item, index) => {
            if (item == card) {
                this.cards.splice(index, 1)
                return true
            }
        })
    }
}

@ccclass
export default class GameModel extends OnEventMode {
    private allCards: cc.SpriteFrame[] = []  //全部卡牌
    private allCardsMap: Map<string, cc.SpriteFrame> = new Map<string, cc.SpriteFrame>()  //全部卡牌
    private backGroundCard: cc.SpriteFrame = null        //背景卡牌
    private cards: Card[] = []        //初始化的卡牌数据
    public currentColor: CardColor = CardColor.red       //当前卡牌颜色
    public currentMasterColor: CardColor = CardColor.red       //当前主卡牌颜色
    private currentPoint: number = 0     //当前卡牌点数
    private currentPlayer: CurrentPlayer = CurrentPlayer.Player1     //当前的玩家
    private currentPlayerNum: playerPeople = playerPeople.twoP       //当前是几人牌局

    private sendCardArea: Card[] = []        //发牌区域
    private recycleCardArea: Card[] = []     //回收牌区域
    private player1CardArea: playerCardArea = new playerCardArea()     //玩家一的牌区
    private player2CardArea: playerCardArea = new playerCardArea()      //玩家二的牌区
    private player3CardArea: playerCardArea = new playerCardArea()     //玩家三的牌区
    private player4CardArea: playerCardArea = new playerCardArea()     //玩家四的牌区
    private holeCardArea: playerCardArea = new playerCardArea()

    private players: Player[] = [
        new Player(1),
        new Player(2),
        new Player(3),
        new Player(4)
    ]      //玩家列表

    private currentRoundWinner: CurrentPlayer = CurrentPlayer.Player1     //当前回合的赢家
    // 当前回合结束
    private isRoundOver: boolean = false

    private player1PointCardArea: playerCardArea = new playerCardArea()     //玩家一的得分牌区
    private player2PointCardArea: playerCardArea = new playerCardArea()      //玩家二的得分牌区
    private player3PointCardArea: playerCardArea = new playerCardArea()     //玩家三的得分牌区
    private player4PointCardArea: playerCardArea = new playerCardArea()     //玩家四的得分牌区

    private cardOrderList: CurrentPlayer[] = []      //出牌顺序

    private currentRoundCards: Card[] = []       //当前回合出的牌
    private playCards: Card[][] = []      //出牌区域
    private playNum: number = 0     //出牌次数
    // 当轮出牌顺序
    private currentRoundOrder: CurrentPlayer[] = []

    private isCanTouch: boolean = true       //是否可以点击
    private firstCardInThisRound: Card = null        //本轮第一张牌

    private isHandleNestPlayer: boolean = true       //是否处理下一位玩家

    private isUNOState: boolean = false   //是否uno
    private isTouchUnoBtn: boolean = false   //是否点击了Uno按钮

    private isGameOver: boolean = false      //是否游戏结束

    // 初始化
    public init() {
        // 获取所有卡牌
        this.getAllCards()
    }

    // 获取全部卡牌
    private getAllCards() {
        // cc.resources.load('/textures/cards', cc.Texture2D, (err, res) => {
        cc.resources.load('/textures/card', cc.Texture2D, (err, res) => {
            if (err) {
                console.warn(err)
            } else {
                for (let j = 0; j < 5; j++) {   //5行
                    for (let i = 0; i < 13; i++) {  //13列
                        if (i > 2 && j === 4) continue  //最后一行第二张之后是无牌的
                        let x = i * CardINF.width + ((i + 0) * CardINF.intervalPixel) + CardINF.marginPixel
                        let y = j * CardINF.height + ((j + 0) * CardINF.intervalPixel) + CardINF.marginPixel
                        let rect = cc.rect(x, y, CardINF.width, CardINF.height)        //获取对应大小区域的卡牌
                        // if (i === 2 && j === 4) {
                        if (i === 4 && j === 0) {
                            this.backGroundCard = new cc.SpriteFrame(res as cc.Texture2D, rect)     //背景图片
                        }
                        this.allCards.push(new cc.SpriteFrame(res as cc.Texture2D, rect))
                    }
                }
                // this.initCardData()     //初始化卡牌数据
                this.initCardDataTianWang()     //初始化卡牌数据
            }
        })
    }

    // 初始化卡牌数据
    public initCardData() {
        for (let n = 0; n < 2; n++) {     //重复两次，108张牌
            //设置卡牌的信息
            for (let j = 0; j < 5; j++) {
                for (let i = 0; i < 13; i++) {
                    if (i >= 2 && j === 4) continue
                    if (j === 0) {
                        this.setCardType(i, CardColor.red)
                    } else if (j === 1) {
                        this.setCardType(i, CardColor.green)
                    } else if (j === 2) {
                        this.setCardType(i, CardColor.blue)
                    } else if (j === 3) {
                        this.setCardType(i, CardColor.yellow)
                    } else {
                        if (i === 0) {
                            this.cards.push(new Card(CardColor.special, CardType.changeColor, null, CardStatus.CLOSE, this.getCardByColorAndIndex(j, i)))
                        } else {
                            this.cards.push(new Card(CardColor.special, CardType.add_4, null, CardStatus.CLOSE, this.getCardByColorAndIndex(j, i)))
                        }
                    }
                }

            }
        }
        this.shuffle(this.cards, 200)

        // 交换牌区
        let tmc = this.sendCardArea
        this.sendCardArea = this.cards
        this.cards = tmc

        this.emit(ListenEventType.INIT_CARD, this.sendCardArea, this.backGroundCard)        //通知UI层背景卡牌
    }

    // 初始化卡牌数据 天王
    public initCardDataTianWang() {
        for (let n = 0; n < 1; n++) {     //重复两次，108张牌
            //设置卡牌的信息
            for (let j = 1; j < 5; j++) {
                for (let i = 2; i < 15; i++) {
                    this.setCardTypeTianWang(i, j)
                }
            }
            
            this.setCardTypeTianWang(18, 1)
            this.setCardTypeTianWang(19, 1)
        }

        

        // this.shuffle(this.cards, 200)

        // 交换牌区
        let tmc = this.sendCardArea
        this.sendCardArea = this.cards
        this.cards = tmc

        this.emit(ListenEventType.INIT_CARD, this.sendCardArea, this.backGroundCard)        //通知UI层背景卡牌
    }

    // 设置卡牌状态
    private setCardType(index: number, color: CardColor) {
        if (index < 10) {
            this.cards.push(new Card(color, CardType.number, index, CardStatus.CLOSE, this.getCardByColorAndIndex(color, index)))   //普通卡
        } else if (index === 10) {
            this.cards.push(new Card(color, CardType.ban, index, CardStatus.CLOSE, this.getCardByColorAndIndex(color, index)))      //ban
        }
        else if (index === 11) {
            this.cards.push(new Card(color, CardType.turn, index, CardStatus.CLOSE, this.getCardByColorAndIndex(color, index)))     //反转卡
        }
        else {
            this.cards.push(new Card(color, CardType.add_2, index, CardStatus.CLOSE, this.getCardByColorAndIndex(color, index)))       //添加2
        }
    }
    // 设置卡牌状态
    private setCardTypeTianWang(index: number, color: CardColor) {
        this.cards.push(new Card(color, CardType.number, index, CardStatus.CLOSE, this.getCardByColorAndIndex(color, index)))   //普通卡
    }
    // 洗牌
    private shuffle(cards: Card[], count: number = 100) {
        for (let i = 0; i < count; ++i) {
            let card1 = Math.floor(Math.random() * cards.length)
            let card2 = Math.floor(Math.random() * cards.length)
            let card = cards[card1]
            cards[card1] = cards[card2]
            cards[card2] = card
        }
    }

    // 根据花色和点数获取卡牌
    private getCardByColorAndIndex(color: CardColor, index: number): cc.SpriteFrame {
        let color_index = `${color}.${index}`
        let frameIndex = CardNodeMap.get(color_index)

        if (frameIndex !== undefined)
            return this.allCards[frameIndex]
        return this.allCards[4]
    }

    // 初始化玩牌顺序
    public initPlayerNum(playerNum: playerPeople) {
        this.currentPlayerNum = playerNum
        switch (this.currentPlayerNum) {
            //设置对应的出牌顺序
            case playerPeople.twoP:
                this.cardOrderList.push(CurrentPlayer.Player1, CurrentPlayer.Player2)
                break;
            case playerPeople.threeP:
                this.cardOrderList.push(CurrentPlayer.Player1, CurrentPlayer.Player2, CurrentPlayer.Player3)
                break;
            case playerPeople.fourP:
                this.cardOrderList.push(CurrentPlayer.Player1, CurrentPlayer.Player2, CurrentPlayer.Player3, CurrentPlayer.Player4)
                break;
        }
    }

    // 发牌（Event）
    public dealCards() {
        // let base: number = this.currentPlayerNum + 2
        // let n: number = base * 3

        // // for (let index = 0; index < 12; index++) {
        // //     this.deal2Hole(10)
        // // }

        // // 设置出牌区域的牌
        // for (let i = 0; i < n; i++) {
        //     if (i % base === CurrentPlayer.Player1) {
        //         this.dealPlayer1(i)
        //     } else if (i % base === CurrentPlayer.Player2) {
        //         this.dealPlayer2(i)
        //     } else if (i % base === CurrentPlayer.Player3) {
        //         this.dealPlayer3(i)
        //     } else {
        //         this.dealPlayer4(i)
        //     }
        // }



        // 打开发牌区最上面的牌
        // this.openSendAreaTopCard()
    }

    /*
    * 发牌
    */
    public netDealCards() {
        // console.log("netDealCards")
        this.dealPlayer1(0)
    }

    private dealPlayer1(i: number) {
        let card = this.sendCardArea.pop()
        card.location = CardLocation.mineCardArea
        card.belongTo = CurrentPlayer.Player1
        let insertIndex = this.player1CardArea.addCards(card)
        console.log(card)
        this.emit(ListenEventType.UI_DEAL_CARDS, card, CurrentPlayer.Player1, i, insertIndex)
    }


    private dealPlayer2(i: number) {
        let card = this.sendCardArea.pop()
        card.location = CardLocation.otherCardArea
        card.belongTo = CurrentPlayer.Player2
        this.player2CardArea.addCards(card)
        this.emit(ListenEventType.UI_DEAL_CARDS, card, CurrentPlayer.Player2, i)
    }
    private dealPlayer3(i: number) {
        let card = this.sendCardArea.pop()
        card.location = CardLocation.otherCardArea
        card.belongTo = CurrentPlayer.Player3
        let insertIndex = this.player3CardArea.addCards(card)
        // console.log("cards", this.player3CardArea.cards)
        this.emit(ListenEventType.UI_DEAL_CARDS, card, CurrentPlayer.Player3, i, insertIndex)
    }
    private dealPlayer4(i: number) {
        let card = this.sendCardArea.pop()
        card.location = CardLocation.otherCardArea
        card.belongTo = CurrentPlayer.Player4
        this.player4CardArea.addCards(card)
        this.emit(ListenEventType.UI_DEAL_CARDS, card, CurrentPlayer.Player4, i)
    }

    private deal2Hole(i: number) {
        let card = this.sendCardArea.pop()
        console.log("deal2Hole", card)
        card.location = CardLocation.holeCardArea
        card.belongTo = CurrentPlayer.Hole
        this.holeCardArea.addCards(card)
        this.emit(ListenEventType.UI_DEAL_CARDS, card, CurrentPlayer.Hole, i)
    }

    // 翻开发牌区最上面的牌
    private openSendAreaTopCard() {
        let card = this.sendCardArea.pop()
        card.location = CardLocation.otherCardArea
        this.recycleCardArea.push(card)
        this.currentColor = card.color
        this.currentPoint = card.index
        this.emit(ListenEventType.UI_OPEN_SENDAREA_CARD, card)
    }


    // 点击卡牌事件（Event）
    public clickCard(card: Card) {
        if (this.currentPlayer !== CurrentPlayer.Player1 || !this.isCanTouch) return        //不是p1或没法点击就跳过
        if (card.location === CardLocation.sendCardArea) {
            let hasCard: Card = this.player1CardArea.findCardByColor(this.currentColor, this.currentPoint)
            if (hasCard) return
            let sendCard = this.sendCardArea.pop()
            sendCard.location = CardLocation.mineCardArea
            this.player1CardArea.addCards(sendCard)
            this.emit(ListenEventType.POST_UI_DEALAREA_TO_PLAYAREA, sendCard, this.currentPlayer, 0)
            let hasCardAgain: Card = this.player1CardArea.findCardByColor(this.currentColor, this.currentPoint)
            if (!hasCardAgain) {
                this.scheduleOnce(() => {
                    this.handleNestPlayer()
                    this.nestPalyer()
                }, 1)
            }
        }
        else if (card.location === CardLocation.mineCardArea) {
            
            let hasCard: Card = this.player1CardArea.findCardByColor(this.currentColor, this.currentPoint)
            if (!hasCard) return
            // if (this.player1CardArea.isShowCard(card, this.currentColor, this.currentPoint)) {
            //     this.player1CardArea.removeCard(card)
            //     card.location = CardLocation.otherCardArea
            //     this.recycleCardArea.push(card)
            //     this.currentColor = card.color
            //     this.currentPoint = card.index
            //     if (this.player1CardArea.isEmptyCard()) {
            //         this.isHandleNestPlayer = false
            //         this.isGameOver = true
            //         this.scheduleOnce(() => {
            //             this.emit(ListenEventType.PLAY_EFFECT, AudioType.game_over)
            //             this.emit(ListenEventType.SHOW_GAMEOVER_PANEL, true)
            //         }, 1.5)
            //     }
            //     this.decideUno()
            //     this.emit(ListenEventType.RECYCLE_CARD, card, this.currentPlayer)
            //     this.isCanTouch = false
            // }
            
            //先让玩家把牌打出去，后面再做判断
            
            this.player1CardArea.removeCard(card)
            card.location = CardLocation.otherCardArea
            this.currentRoundCards.push(card);
            if (this.player1CardArea.isEmptyCard()) {
                this.isHandleNestPlayer = false
                this.isGameOver = true
                this.scheduleOnce(() => {
                    this.emit(ListenEventType.PLAY_EFFECT, AudioType.game_over)
                    this.emit(ListenEventType.SHOW_GAMEOVER_PANEL, true)
                }, 1.5)
            }
            //設置player1CardArea的card可以点击
            this.player1CardArea.cards.map((card) => {
                card.canClick = true
            })

            this.emit(ListenEventType.RECYCLE_CARD, card, this.currentPlayer)
            this.isCanTouch = false
            

            //打印被选中的牌
            // this.player1CardArea.cards.map((card) => {
            //     if (card.selected) {
            //         console.log(card)
            //     }
            // })
            
            // 判断这张牌是否可以选
            // 如果可以
            // this.emit(ListenEventType.SELECT_CARD, card, this.currentPlayer)
        }
        else {
            console.log('无效区')
        }

    }

    // 下一位玩家（Event）
    public nestPlayerDealCard() {
        this.handleNestPlayer()
        this.nestPalyer()
    }

    //轮到下一位玩家出牌（Event）
    private nestPalyer() {
        if (!this.isHandleNestPlayer) return
        if (this.isUNOState && !this.isTouchUnoBtn) {
            this.scheduleOnce(() => {
                if (!this.isTouchUnoBtn) {
                    // 没有点击uno按钮派两张牌
                    for (let i = 0; i < 2; i++) {
                        let card = this.sendCardArea.pop()
                        card.location = CardLocation.mineCardArea
                        this.player1CardArea.addCards(card)
                        this.emit(ListenEventType.POST_UI_DEALAREA_TO_PLAYAREA, card, CurrentPlayer.Player1, i)
                    }
                }
                this.isTouchUnoBtn = false
                this.isUNOState = false
                this.scheduleOnce(() => { this.nestPlayerDeal() }, 0.5)
            }, 1.5)
        } else {
            this.nestPlayerDeal()
        }

    }

    private nestPlayerDeal() {
        if (this.currentPlayer === CurrentPlayer.Player1)
            this.isCanTouch = true
        this.emit(ListenEventType.POST_UI_NEXT_BAR, this.currentPlayer)
        this.dealNestAction()
    }

    public changeCardInf(card: Card) {
        if (card.color !== CardColor.special) {
            this.currentColor = card.color
            this.currentPoint = card.index
            this.emit(ListenEventType.POST_UI_CARD_COLOR, this.currentColor)
        } else {
            this.currentPoint = null
        }
    }

    private handleNestPlayer() {
        this.calculateScore()
        if (this.isRoundOver)
            console.log('当前回合结束，当前回合的胜利者是：', this.currentRoundWinner)

        // 如果当前回合结束，下一位出牌玩家是当前回合的胜利者
        if (this.isRoundOver) {
            this.currentPlayer = this.currentRoundWinner
            return
        }

        let loc = this.cardOrderList.indexOf(this.currentPlayer)
        loc = loc + 1
        if (loc >= this.cardOrderList.length) {
            loc = 0
        }
        this.currentPlayer = this.cardOrderList[loc]
    }

    private getPlayerAreaByCurrent() {
        let playerArea: playerCardArea = null
        switch (this.currentPlayer) {
            case CurrentPlayer.Player1: playerArea = this.player1CardArea; break;
            case CurrentPlayer.Player2: playerArea = this.player2CardArea; break;
            case CurrentPlayer.Player3: playerArea = this.player3CardArea; break;
            case CurrentPlayer.Player4: playerArea = this.player4CardArea; break;
        }
        return playerArea;
    }

    private getPlayerByCurrent(): Player {
        return this.players[this.currentPlayer]
    }

    //当轮结算，计算得分
    private calculateScore() {
        // console.log('计算得分', this.currentRoundCards.length, this.currentPlayer)
        if (this.currentRoundCards.length === 1 && this.currentPlayer != CurrentPlayer.Player1) {
            this.firstCardInThisRound = this.currentRoundCards[0]
            let suitableCards = getSuitableCards(this.player1CardArea.cards, this.currentMasterColor, this.firstCardInThisRound)
            this.player1CardArea.cards.map((card) => {
                card.canClick = false
                if (suitableCards.indexOf(card) >= 0)
                    card.canClick = true
            })
            this.emit(ListenEventType.POST_UI_SUITABLE_CARDS, this.player1CardArea.cards)
        }

        if (this.currentRoundCards.length >= this.currentPlayerNum + 2) {
            // 计算得分 todo
            this.playCards.push(this.currentRoundCards);
            
            let maxCard = this.currentRoundCards[0]
            for (let i = 1; i < this.currentRoundCards.length; i++) {
                let card = this.currentRoundCards[i]
                // console.log(card)
                if (card.greater(maxCard, this.currentColor)) {
                    // console.log("greater")
                    maxCard = card;
                }
            }
            let currentWinPlayer = maxCard.belongTo // 当轮赢家
            // 使用reduce计算得分
            let points = this.currentRoundCards.reduce((pre, cur) => {
                return pre + cur.getCardPoint()
            }, 0 as number);
            
            // console.log(currentWinPlayer, "得分", points)
            this.players[currentWinPlayer].addPoints(points)
            let totalPoints = this.players[currentWinPlayer].getPonits()
            // console.log(currentWinPlayer, "总得分", totalPoints)
            this.emit(ListenEventType.POST_UI_POINTS, currentWinPlayer, totalPoints)
            // console.log("maxCard", maxCard)
            this.currentRoundCards = [];
            this.isRoundOver = true // 设置回合结束标志
            this.currentRoundWinner = currentWinPlayer // 设置回合胜利者
            this.firstCardInThisRound = null
        } else {
            this.isRoundOver = false
        }
    }
    

    // private getWin

    // 处理下一位玩家出牌逻辑
    private dealNestAction() {
        let playerArea = this.getPlayerAreaByCurrent()
        if (this.currentPlayer !== CurrentPlayer.Player1) {
            // let card = playerArea.findCardByColor(this.currentColor, this.currentPoint)
            let card = playerArea.findCardByColor(this.currentColor, this.currentPoint)
            if (!card) {
                let getCard: Card = this.sendCardArea.pop()
                getCard.location = CardLocation.otherCardArea
                playerArea.addCards(getCard)
                this.emit(ListenEventType.POST_UI_DEALAREA_TO_PLAYAREA, getCard, this.currentPlayer, 0)
                let hasCard = playerArea.findCardByColor(this.currentColor, this.currentPoint)
                if (hasCard) {
                    playerArea.removeCard(hasCard)
                    hasCard.location = CardLocation.otherCardArea
                    this.currentRoundCards.push(card);
                    // this.calculateScore()

                    this.scheduleOnce(() => {
                        this.emit(ListenEventType.POST_UI_ROBOT_DEAL_CARD, hasCard, this.currentPlayer)
                        this.scheduleOnce(() => {
                            this.handleUNO(playerArea)
                        }, 0.5)
                    }
                        , 1)
                } else {
                    this.scheduleOnce(() => {
                        this.handleNestPlayer()
                        this.nestPalyer()
                    }, 1)
                }
            } else {
                playerArea.removeCard(card)
                card.location = CardLocation.otherCardArea
                this.getPlayerByCurrent().addPlayedCard(card) // 记录玩家出牌
                this.currentRoundOrder.push(this.currentPlayer) // 记录出牌顺序
                this.playNum++;// 记录出牌次数
                this.currentRoundCards.push(card);
                // this.calculateScore()

                this.scheduleOnce(() => {
                    this.emit(ListenEventType.POST_UI_ROBOT_DEAL_CARD, card, this.currentPlayer)
                    this.scheduleOnce(() => {
                        this.handleUNO(playerArea)
                    }, 0.3)
                }, 1)
                if (playerArea.isEmptyCard()) {
                    this.isHandleNestPlayer = false
                    this.isGameOver = true
                    this.scheduleOnce(() => {
                        this.emit(ListenEventType.PLAY_EFFECT, AudioType.game_over)
                        this.emit(ListenEventType.SHOW_GAMEOVER_PANEL, false)
                    }, 1.5)
                }
            }
        }
    }

    // 处理UNO
    private handleUNO(playerArea: playerCardArea) {
        if (playerArea.isRemainOneCard()) {
            if (Math.floor(Math.random() * 5) === 1) {
                this.scheduleOnce(() => {
                    for (let i = 0; i < 2; i++) {
                        let card = this.sendCardArea.pop()
                        card.location = CardLocation.otherCardArea
                        playerArea.addCards(card)
                        this.emit(ListenEventType.POST_UI_DEALAREA_TO_PLAYAREA, card, this.currentPlayer, i)
                    }
                }, 1)
            }
            else {
                this.emit(ListenEventType.POST_UI_UNO, this.currentPlayer)
            }
        }
    }

    private getLastPlayer(): CurrentPlayer {
        let index = this.cardOrderList.findIndex((item) => {
            return item == this.currentPlayer
        })
        if (index === 0) {
            index = this.cardOrderList.length - 1
        } else {
            index = index - 1
        }
        return this.cardOrderList[index]
    }

    // 添加牌(2/4)
    private handleAddEff(num: number) {
        this.handleNestPlayer()
        let playerArea = this.getPlayerAreaByCurrent()
        for (let i = 0; i < num; i++) {
            let card = this.sendCardArea.pop()
            if (this.currentPlayer === CurrentPlayer.Player1) {
                card.location = CardLocation.mineCardArea
            } else {
                card.location = CardLocation.otherCardArea
            }
            playerArea.addCards(card)
            this.emit(ListenEventType.POST_UI_DEALAREA_TO_PLAYAREA, card, this.currentPlayer, i)
        }
    }

    //禁止出牌
    private handleBanEff() {
        this.handleNestPlayer()
        this.handleNestPlayer()
        this.nestPalyer()
    }

    //翻转出牌顺序
    private handleTurnEff() {
        this.cardOrderList.reverse()
        if (this.currentPlayerNum !== playerPeople.twoP) { this.handleNestPlayer() }
        this.nestPalyer()
    }

    // 添加2张牌
    private handleAdd2Eff() {
        this.handleAddEff(2)
        this.scheduleOnce(() => {
            this.handleNestPlayer()
            this.nestPalyer()
        }, 1)
    }

    // 添加4张牌（选择颜色）
    private handleAdd4Eff() {
        this.handleAddEff(4)
        this.scheduleOnce(() => {
            if (this.getLastPlayer() !== CurrentPlayer.Player1) {
                let color: BtnColor = Math.floor(Math.random() * 4)
                this.handleNestPlayer()
                this.alterColor(color + 1)
            } else {
                this.handleNestPlayer()
                this.emit(ListenEventType.POST_UI_SHOW_SELECTCOLOR)
            }
        }, 1)
    }

    //变更颜色
    private changeColor(color: BtnColor) {
        this.getCurrentColor(color)
        this.handleNestPlayer()
        this.nestPalyer()
    }

    // 动画处理完毕
    public aniamtionOver(type: CardType, color?: number) {
        switch (type) {
            case CardType.add_2: this.handleAdd2Eff(); break;
            case CardType.ban: this.handleBanEff(); break;
            case CardType.turn: this.handleTurnEff(); break;
            case CardType.add_4: this.handleAdd4Eff(); break;
            case CardType.changeColor: this.changeColor(color); break;
        }
    }

    private getCurrentColor(color: BtnColor) {
        switch (color) {
            case BtnColor.blue: this.currentColor = CardColor.blue; break;
            case BtnColor.green: this.currentColor = CardColor.green; break;
            case BtnColor.red: this.currentColor = CardColor.red; break;
            case BtnColor.yellow: this.currentColor = CardColor.yellow; break;
        }
        this.emit(ListenEventType.POST_UI_CARD_COLOR, this.currentColor)
    }


    // 更改颜色(Evnet)
    public alterColor(color: BtnColor) {
        this.getCurrentColor(color)
        this.isHandleNestPlayer = true
        this.nestPalyer()
    }

    // 是否uno（Event）
    public isUNO() {
        this.isTouchUnoBtn = true
        if (this.player1CardArea.isRemainOneCard()) {
            this.isUNOState = true
            this.emit(ListenEventType.POST_UI_UNO, CurrentPlayer.Player1)

        } else {
            this.isUNOState = false
            this.isTouchUnoBtn = false
        }
    }

    //判断是否UNO
    private decideUno() {
        if (this.player1CardArea.isRemainOneCard()) {
            this.isUNOState = true
        }
        else {
            this.isUNOState = false
        }
    }

    // 获取对应类型的卡牌(Event)
    public getCardByType(type: explainType) {
        let arr = []
        switch (type) {
            case explainType.normal:
                for (let i = 1; i < 5; i++) {
                    for (let j = 2; j < 15; j++) {
                        arr.push(this.getCardByColorAndIndex(i, j))
                    }
                }
                arr.push(this.getCardByColorAndIndex(1, 18))
                arr.push(this.getCardByColorAndIndex(1, 19))
                break;
            case explainType.add_2:
                for (let i = 0; i < 4; i++) {
                    arr.push(this.getCardByColorAndIndex(i, 12))
                }
                break;
            case explainType.ban:
                for (let i = 0; i < 4; i++) {
                    arr.push(this.getCardByColorAndIndex(i, 10))
                }
                break;
            case explainType.turn:
                for (let i = 0; i < 4; i++) {
                    arr.push(this.getCardByColorAndIndex(i, 11))
                }
                break;
            case explainType.add_4:
                arr.push(this.getCardByColorAndIndex(4, 1))
                break;
            case explainType.change_color:
                arr.push(this.getCardByColorAndIndex(4, 0))
                break;

        }
        this.emit(ListenEventType.RETURN_CARD_SPRITEFRAME_BY_TYPE, arr)
    }

    // 游戏结束（Event）
    public postIsGameOver() {
        this.emit(ListenEventType.POST_UI_ISGAMEOVER, this.isGameOver)
    }
}
